//
//  PaymentManager.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/1.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "PaymentManager.h"
#import "ZCBaseUserManager.h"
#import "UIImage+SubImage.h"

NSString *wxAppName = @"gh_79dd5bd44d4c";

@interface PaymentManager()

@property (assign, nonatomic) WXMiniProgramType type;

@property (nonatomic, copy) void(^callback)(id info);

@end


@implementation PaymentManager

+ (instancetype)sharedManager {
    static PaymentManager *obj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        obj = [[PaymentManager alloc] init];
        // 环境配置
        obj.type = WXMiniProgramTypeRelease;
    });
    return obj;
}

// MARK: - WXApiDelegate

- (void)weiXinPayWithDic:(NSDictionary *)wechatPayDic {
    PayReq *req = [[PayReq alloc] init];
    
    req.openID = [wechatPayDic objectForKey:@"appId"];
    req.timeStamp = [[wechatPayDic objectForKey:@"timeStamp"] intValue];
    req.package = [wechatPayDic objectForKey:@"packages"];
    req.nonceStr = [wechatPayDic objectForKey:@"nonceStr"];
    req.sign = [wechatPayDic objectForKey:@"paySign"];
    
    req.partnerId = [wechatPayDic objectForKey:@"partnerId"];
    req.prepayId = [wechatPayDic objectForKey:@"prepayId"];
    
    [WXApi sendReq:req];
    [WXApi openWXApp];
}

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) { //支付回调
        PayResp *response = (PayResp *)resp;
        if (_delegate && [_delegate respondsToSelector:@selector(managerDidRecvPaymentResponse:)]) {
            [_delegate managerDidRecvPaymentResponse:response];
        }
    }
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]]) { //小程序回调
        WXLaunchMiniProgramResp *res = (WXLaunchMiniProgramResp *)resp;
        if (_delegate && [_delegate respondsToSelector:@selector(managerDidRecvMiniResponse:)]) {
            [_delegate managerDidRecvMiniResponse:res];
        }
    }

    if ([resp isKindOfClass:[SendMessageToWXResp class]]) { //分享回调
        SendMessageToWXResp *res = (SendMessageToWXResp *)resp;
        if (_delegate && [_delegate respondsToSelector:@selector(managerDidRecvShareResponse:)]) {
            [_delegate managerDidRecvShareResponse:res];
        }
    }

    if ([resp isKindOfClass:[SendAuthResp class]]) { //分享回调
        SendAuthResp *res = (SendAuthResp *)resp;
        if (_delegate && [_delegate respondsToSelector:@selector(managerDidRecvAuthResponse:)]) {
            [_delegate managerDidRecvAuthResponse:res];
        }
    }
}

- (void)loadWeiXinMiniProgram:(NSString *)orderId {
    WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
    req.userName = wxAppName;
    ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
    ZCBaseUserModel *userModel = manager.userModel;
    req.path = [NSString stringWithFormat:@"pages/pay/pay?order_id=%@&isApp=1&token=%@&uid=%@&from=app",
                orderId,userModel.member.accessToken,
                userModel.member.idstr];
    req.miniProgramType = self.type;
    [WXApi sendReq:req];
}

- (void)loadWeiXinMiniProgram2Recharge {
    WXLaunchMiniProgramReq *req = [WXLaunchMiniProgramReq object];
    req.userName = wxAppName;
    ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
    ZCBaseUserModel *userModel = manager.userModel;
    req.path = [NSString stringWithFormat:@"pages/Earnings/topUp/topUp?isApp=1&token=%@&uid=%@&from=app",
                userModel.member.accessToken,
                userModel.member.idstr];
    req.miniProgramType = self.type;
    [WXApi sendReq:req];
}

/// 分享给微信好友
- (void)share2WeiXinFirendList:(id)obj {
    WXMediaMessage *message = [WXMediaMessage message];
    if ([obj isKindOfClass:[UIImage class]]) {
        WXImageObject *imgobj = [WXImageObject object];
        imgobj.imageData = UIImageJPEGRepresentation(obj, 0.5);
        message.mediaObject = imgobj;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.scene = WXSceneSession;
        req.message = message;
        req.bText = NO;
        [WXApi sendReq:req];//发送对象实例
    }
    if ([obj isKindOfClass:[NSArray class]]) {
        NSArray *arr = (NSArray *)obj;
        NSString *maintitle = arr.firstObject;
        NSString *subtitle = arr[1];
        NSString *thumbimvurl = arr[2];
        NSString *url = arr.lastObject;
        NSData *imvdata = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumbimvurl]];
        
        message.title = maintitle;
        message.description = subtitle;
        UIImage *img = [UIImage imageWithData:imvdata];
        img = [UIImage imageWithData:UIImageJPEGRepresentation(img, 0.3)];
        img = [img rescaleImageToSize:(CGSize){50,50}];
        [message setThumbImage:img];
        
        WXWebpageObject *webo = [WXWebpageObject object];
        webo.webpageUrl = url;
        message.mediaObject = webo;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.scene = WXSceneSession;
        req.message = message;
        req.bText = NO;
        [WXApi sendReq:req];//发送对象实例
    }
}
/// 分享到朋友圈
- (void)share2WeiXinCycle:(id)obj {
    WXMediaMessage *message = [WXMediaMessage message];
    if ([obj isKindOfClass:[UIImage class]]) {
        WXImageObject *imgobj = [WXImageObject object];
        imgobj.imageData = UIImageJPEGRepresentation(obj, 0.5);
        message.mediaObject = imgobj;
    }
    if ([obj isKindOfClass:[NSArray class]]) { //数组来分享对象【标题、媒体地址】
        NSArray *arr = (NSArray *)obj;
        NSString *maintitle = arr.firstObject;
        id obj = arr.lastObject;
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *txt = [NSString stringWithFormat:@"%@",obj];
            if ([txt hasPrefix:@"video://"]) {
                WXVideoObject *videobj = [WXVideoObject object];
                videobj.videoUrl = [NSString stringWithFormat:@"%@",[txt substringFromIndex:8]];
                message.mediaObject = videobj;
                message.title = maintitle;
            }
            if ([txt hasPrefix:@"http://"]||[txt hasPrefix:@"https://"]) {
                WXWebpageObject *webo = [WXWebpageObject object];
                webo.webpageUrl = txt;
                message.mediaObject = webo;
                NSString *thumbimvurl = arr[2];
                NSData *imvdata = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumbimvurl]];
                UIImage *img = [UIImage imageWithData:imvdata];
                img = [UIImage imageWithData:UIImageJPEGRepresentation(img, 0.3)];
                img = [img rescaleImageToSize:(CGSize){50,50}];
                [message setThumbImage:img];
                message.title = maintitle;
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.scene = WXSceneSession;
                req.message = message;
                req.bText = NO;
            }
        }
    }
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.scene = WXSceneTimeline;
    req.message = message;
    req.bText = NO;
    [WXApi sendReq:req];//发送对象实例
}
/// 认证
- (void)auth2WeiXinWithVC:(UIViewController *)vc callback:(void(^)(NSString *msg))callback {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"yrgios";
        [WXApi sendReq:req];
    } else {
        callback(@"你还没有安装微信");
    }
}

- (void)login2WeiXinWithCallback:(void(^)(NSString *msg))callback {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"yrgios";
        [WXApi sendReq:req];
    } else {
        callback(@"你还没有安装微信");
    }
}

- (void)loginAliPayWithOrderSignStr:(NSString *)str callback:(void(^)(NSDictionary *dict))callback {
    self.callback = callback;
    [[AlipaySDK defaultService] payOrder:str fromScheme:@"mall.weizhegou.shop" callback:callback];
}

- (void)setAliPayCallback:(NSDictionary *)info {
    if (self.callback) {
        self.callback(info);
    }
}

- (void)loadWXPayWithWithOrderSignInfo:(NSDictionary *)info {
    PayReq *req = [[PayReq alloc] init];
    req.partnerId = [info valueForKey:@"partnerid"];
    req.prepayId = [info valueForKey:@"prepayid"];
    req.nonceStr = [info valueForKey:@"noncestr"];
    req.timeStamp = [[info valueForKey:@"timestamp"] intValue];
    req.sign = [info valueForKey:@"sign"];
    req.package = [info valueForKey:@"package"];
    [WXApi sendReq:req];
}


//- (void)aliPayAction {
//    // 重要说明
//    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
//    /*============================================================================*/
//    /*=======================需要填写商户app申请的===================================*/
//    /*============================================================================*/
//    NSString *appID = @"2016062601555027";
//
//    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
//    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
//    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
//    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
//    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
//    NSString *rsa2PrivateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDA0mo5OqYABeQahwtxcxA/Z9tE6UREGeJTZdHi7c0dOEmn+IIfxL6FkBxlwrJmoHR8uB/oPvdRh2m2MDWfd83zMlKGvpUC/SVvF0BUskDX+VEvGTdBQ1GcOcEZrExx4rk8IRM4Xxlxpf1+fdZ251IB+jA8IJHP/y/kFZRzoGcjKfaGSIZ1reQJy0ibvFAxOKBpttMNQGWUCSY4dvAcDqpJrfKGJU/eJYBzHx5owhDq02J71VqCf4D+XhzEoRbQikSSuozKhriwhCetfruYd2Jrcp3BtS4EhycwKrcPbQh0EFOeCqKhoOHhZVMV6YFwI33W/l26CCop6I+qBh0T4CZnAgMBAAECggEAS4ghJBndPNUR7XJJAT/ZdXzxX6UgoKyjA5g3B3Wvi2qpL6shDeC74QX6mcISsDDacKCPnyJLLxykREHOP5Fmk4V63l15cZpIN6QcBxFsZS28p35xLpd4OIJHKg9cQqBVf0BVjxdxmBs1mX8hq6IhdbTTgDoh5CBKWkY5yLFktVjkrXItc1beXN20UoMgIl08cfP3LQsIZOt4DRGSykSFbLp0XpKBDlyaUfrUBE3ewyJabsGLr+WGhRd3XL7KOT7OcezxYNgQ5ScSdLDUauEiWNO4BWaHB+6CmImmG1A88qQjcn4ZZRxW4rwmtr3TaIUF1QSfzphe7rRHdF3ipYP7wQKBgQDg13TTn//uYfoCkx60K29JWSKe13s2YFotfGCk2xZtoG6uB27NwIC9TgygU5jwO7m5r5psjBxRC+CdyrrlyIhe21flI2iyUdif55LyShgKXGsxM4eHAlousleHchj4Zpe1go2pq5QVc4rR+GgVn44fzhPKGrBXWfxuQLYDFDhgvQKBgQDbiwTkKSlbA1v91aUAkJ9PahVFCFsbvLMSBKqtlC66DlL2ELar6NsAvuh4gcvW4aq3OeHLuW1BO4FH45SXYhBW/Y3cPzwpqIrn8eynIAwV/CQ271wJoGUv8e+ZgdKBJVAwv6aoCWDXm2AIyOXqwRpKOulAizziTEK0l0pJq6pP8wKBgQCB59pG/zWWnKMfY7Mks8e7oDVhguxccXUIvMj11uNxeXUZNZAubp+zQGoJI+PEQS3AfBYDyzv9E5i2clBjvOYVsDNrX3b5OFKpqNl9BZQ4QEdqiPQv7AsA2ee6iRCmTFgw9fo1Yr3PWw+E2zn/7EzoUV+bsKnb/lDbvqWqx77/HQKBgC1B3UJDkfjnGmGbVyZkqdKvJa9TZ6SyI6AFQkICGBfWuBdtnpqVp//hWv7skt67KnwW/IsIsJMP9zigm5MRbhjgsAvFJVvZGLlzz7ssChHGJpkEgs6hN/rIPwJAFur0jDFgcLSXKlWH/CYTdAIOyKKgvlDF40krO10LCw9gyf0tAoGAJ5fbYPTq4lI8QmIOIDEhNcgxDJhjzDMF/Tjqt8/yjPnnC5J8Tgiy/Q8t/fmM/noKXyGZuStd/3xdlLLSL7FFCkRxfzVO4jtKfxktATpjcALeUV83QaO5rQgf1c8r97qqxt6wihyyGehLCOMYwzr2rlqEsRoQNeXyKlMTiBOEtUg=";
//    NSString *rsaPrivateKey = @"";
//    /*============================================================================*/
//    /*============================================================================*/
//    /*============================================================================*/
//
//    //partner和seller获取失败,提示
//    if ([appID length] == 0 ||
//        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
//    {
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
//                                                                       message:@"缺少appId或者私钥,请检查参数设置"
//                                                                preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了"
//                                                         style:UIAlertActionStyleDefault
//                                                       handler:^(UIAlertAction *action){
//
//                                                       }];
//        [alert addAction:action];
//        UIViewController *topvc = [self visibleViewController];
//        [topvc presentViewController:alert animated:YES completion:^{ }];
//        return;
//    }
//
//    /*
//     *生成订单信息及签名
//     */
//    //将商品信息赋予AlixPayOrder的成员变量
//    APOrderInfo* order = [APOrderInfo new];
//
//    // NOTE: app_id设置
//    order.app_id = appID;
//
//    // NOTE: 支付接口名称
//    order.method = @"alipay.trade.app.pay";
//
//    // NOTE: 参数编码格式
//    order.charset = @"utf-8";
//
//    // NOTE: 当前时间点
//    NSDateFormatter* formatter = [NSDateFormatter new];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    order.timestamp = [formatter stringFromDate:[NSDate date]];
//
//    // NOTE: 支付版本
//    order.version = @"1.0";
//
//    // NOTE: sign_type 根据商户设置的私钥来决定
//    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
//
//    // NOTE: 商品数据
//    order.biz_content = [APBizContent new];
//    order.biz_content.body = @"我是测试数据";
//    order.biz_content.subject = @"1";
//    order.biz_content.out_trade_no = @"20180411800001";//[self generateTradeNO]; //订单ID（由商家自行制定）
//    order.biz_content.timeout_express = @"30m"; //超时时间设置
//    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", 0.01]; //商品价格
//
//    //将商品信息拼接成字符串
//    NSString *orderInfo = [order orderInfoEncoded:NO];
//    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
//    NSLog(@"orderSpec = %@",orderInfo);
//
//    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
//    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
//    NSString *signedString = nil;
//    APRSASigner* signer = [[APRSASigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
//    if ((rsa2PrivateKey.length > 1)) {
//        signedString = [signer signString:orderInfo withRSA2:YES];
//    } else {
//        signedString = [signer signString:orderInfo withRSA2:NO];
//    }
//
//    // NOTE: 如果加签成功，则继续执行支付
//    if (signedString != nil) {
//        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
//        NSString *appScheme = @"alisdkdemo";
//
//        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
//        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
//                                 orderInfoEncoded, signedString];
//
//        // NOTE: 调用支付结果开始支付
//        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//            NSLog(@"reslut = %@",resultDic);
//        }];
//    }
//}

- (UIViewController *)visibleViewController {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;;
    return [self getVisibleViewControllerFrom:rootViewController];
}

- (UIViewController *)getVisibleViewControllerFrom:(UIViewController *) vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [self getVisibleViewControllerFrom:vc.presentedViewController];
        } else {
            return vc;
        }
    }
}

@end
